package com.chrray.position.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
import java.util.UUID;

import static jodd.io.FileUtil.mkdirs;

/**
 * @author LM
 * @date 2023/11/1 16:38
 */
public class QrCodeUtil {
    private static final String CHARSET = "utf-8";

    private static final String FORMAT_NAME = "JPG";

// 需要注意 颜色码需是16进制字符串

    private static final int HUA_SE = 0xFFFF8C00; // 码颜色

    private static final int DI_SE = 0xFFEE82EE; // 底色



// 二维码尺寸

    private static final int QRCODE_SIZE = 800;

// LOGO宽度

    private static final int WIDTH = 50;

// LOGO高度

    private static final int HEIGHT = 50;

    private static BufferedImage createImage(String content,

                                             boolean needCompress) throws Exception {

        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();

        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);

        hints.put(EncodeHintType.MARGIN, 1);

        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,

                BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);

        int width = bitMatrix.getWidth();

        int height = bitMatrix.getHeight();

        BufferedImage image = new BufferedImage(width, height,

                BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {

            for (int y = 0; y < height; y++) {

                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF00FF7F

                        : 0xFFFFFFFF);

            }

        }
        return image;
    }


    public static String encode(String content,

                                String destPath,boolean needCompress) throws Exception {

        BufferedImage image = QrCodeUtil.createImage(content,

                needCompress);

        mkdirs(destPath);

        String s = UUID.randomUUID().toString();

        String file = s+".jpg";

        ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));

        return file;

    }




}
